import {
  editTopicManage,
  selectCuesTopicManage,
  selectTopicManageTreeAssignOrganization,
  selectTopicManageTreeLinkageOrganization,
} from '@/services/api/api-cues-topic';
import { CheckCircleOutlined, CheckCircleTwoTone, UserOutlined } from '@ant-design/icons';
import {
  ModalForm,
  ProFormCascader,
  ProFormDateTimePicker,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { useAccess } from 'umi';
import { Avatar, Button, Cascader, Form, message, Segmented } from 'antd';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';
import React, { useRef, useState } from 'react';

interface TableTopicManageEditProps {
  item: CuesTopicData.TopicPage;
  mode: 'apply' | 'release';
  onRefurbish: () => void;
}

const TableTopicManageEdit: React.FC<TableTopicManageEditProps> = ({ item, mode, onRefurbish }) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  const [loading, setLoading] = useState(false);

  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  /**
   * 联动单位数据
   */
  const [treeLinkageOrganizationData, setTreeLinkageOrganizationDataState] = useState<DataNode[]>();

  // /**
  //  * 行业
  //  */
  // const [industryIds, setIndustryIdsState] = useState<any[]>([]);

  /**
   * 选题计划详情
   */
  const [dataTopicDetails, setDataTopicDetailsState] = useState<CuesTopicData.TopicSelectManage>();

  /**
   * 是否有指派
   */
  const [isLinkage, setIsLinkageState] = useState<boolean>(false);


  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadSelectTopicManageTreeAssignOrganization = async () => {
    try {
      const response = await selectTopicManageTreeAssignOrganization({ id: item.id });
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载 保存 联动 单位
   */
  const loadSelectTopicManageTreeLinkageOrganization = async () => {
    try {
      const response = await selectTopicManageTreeLinkageOrganization({
        id: item.id,
      });
      if (response.code === 0) {
        setTreeLinkageOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  // /**
  //  * 加载 行业 列表
  //  * @param key
  //  */
  // const loadCuesIndustryData = async () => {
  //   try {
  //     const response = await listCuesIndustry();

  //     setIndustryIdsState(
  //       response.data.map((item) => {
  //         return { label: item.name, value: item.id };
  //       }),
  //     );
  //   } catch (error) {}
  // };

  /**
   * 加载 选题计划详情
   * @param key
   */
  const loadCuesTopicDetails = async () => {
    setLoading(true);
    try {
      const response = await selectCuesTopicManage({ id: item.id });
      const { code, data } = response;
      if (code === 0) {
        setDataTopicDetailsState(data);
        formRef.current?.setFieldsValue({
          grade: data.grade + '',
          name: data.name,
          // industryIds: data.industryIds,
          // labels: data.labelNames,
          content: data.content,
          deadlineTime: data.deadlineTime,
          assignOrganizationIds: data.cascaderAssignOrganizations,
          linkageOrganizationIds: data.cascaderLinkageOrganizations,
          linkageDescribes: data.linkageDescribes,
        });

        setLoading(false);
      }
    } catch (error) {}
  };

  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <DrawerForm
      key="edit_topic_drawer_form"
      title={mode === 'apply' ? '申请' : '修改发布'}
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
      }}
      loading={loading}
      formRef={formRef}
      trigger={
        <Button key="button_release_state_change" type="primary" icon={<CheckCircleOutlined />}>
          {mode === 'apply' ? '申请' : '修改发布'}
        </Button>
      }
      onVisibleChange={(visible: boolean) => {
        if (visible) {
          //加载权限树请求网络
          loadSelectTopicManageTreeAssignOrganization();
          loadSelectTopicManageTreeLinkageOrganization();
          // loadCuesIndustryData();
          loadCuesTopicDetails();
        }
      }}
      onValuesChange={(values) => {
        if (values.linkageOrganizationIds !== undefined) {
          setIsLinkageState(values.linkageOrganizationIds.length > 0);
        }
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            defaultDoms,
            <ModalForm
              key={'modal_form_release_state_release'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />

                  {mode === 'apply' ? '是否提交' : '是否发布'}
                </>
              }
              trigger={
                <Button
                  key="button_release_state_release"
                  type="primary"
                  style={{
                    background: '#87d068',
                  }}
                  icon={<CheckCircleOutlined />}
                >
                  {mode === 'apply' ? '提交' : '发布'}
                </Button>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                // bodyStyle: { textAlign: 'center' },
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async (values) => {
                props.submit();
                return true;
              }}
            />,
          ];
        },
      }}
      onFinish={async (values) => {
        if (values.deadlineTime === undefined) {
          message.warning('截止时间');
          return;
        }

        const response = await editTopicManage({
          ...values,
          id: item.id,
          recordState: mode === 'apply' ? 1 : 3, //发布
          updateSource: 1, //创建来源 1、PC 2、小程序
        });

        if (response.code === 0) {
          message.success('提交成功');
          onRefurbish();
          return true;
        } else {
          return false;
        }
      }}
    >
      <Form.Item label="分类" name="grade" rules={[{ required: true, message: '请选择分类' }]}>
        <Segmented
          defaultValue={item.grade + ''}
          onChange={(value) => {
            formRef.current?.setFieldsValue({
              grade: value,
            });
          }}
          options={[
            {
              label: (
                <div style={{ padding: 4 }}>
                  <Avatar style={{ backgroundColor: '#f50' }} icon={<UserOutlined />} />
                  <div>重大</div>
                </div>
              ),
              value: '1',
            },
            {
              label: (
                <div style={{ padding: 4 }}>
                  <Avatar style={{ backgroundColor: '#ffd591' }} icon={<UserOutlined />} />
                  <div>重要</div>
                </div>
              ),
              value: '2',
            },
            {
              label: (
                <div style={{ padding: 4 }}>
                  <Avatar style={{ backgroundColor: '#2db7f5' }} icon={<UserOutlined />} />
                  <div>一般</div>
                </div>
              ),
              value: '3',
            },
          ]}
        />
      </Form.Item>

      <ProFormText
        width="xl"
        label="标题"
        name="name"
        rules={[{ required: true, message: '请输入标题' }]}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />
      {/* <ProFormSelect
        width="xl"
        name="industryIds"
        label="行业"
        options={industryIds}
        fieldProps={{
          mode: 'multiple',
          allowClear: true,
        }}
        extra={'最少输入一个'}
        rules={[{ required: true, message: '请选择最少一个行业' }]}
      />

      <Form.Item
        label="标签"
        name="labels"
        extra={'最少输入一个'}
        rules={[{ required: true, message: '请选择最少一个标签' }]}
      >
        <TagGroup />
      </Form.Item> */}

      <ProFormTextArea
        width="xl"
        label="计划描述"
        name="content"
        fieldProps={{
          rows: 6,
          allowClear: true,
          maxLength: 50000,
          placeholder: '请输入描述（支持换行输入）',
          showCount: true,
        }}
        rules={[{ required: true, message: '请输入描述' }]}
      />
      <ProFormDateTimePicker
        width="xl"
        name="deadlineTime"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                fontSize: 14,
                paddingRight: 4,
              }}
            >
              *
            </span>
            截止时间
          </>
        }
        extra="到达设定的截止时候后，系统会关闭该指令"
        fieldProps={{
          minDate: dayjs(),
          presets: [
            { label: '后3天', value: dayjs().add(3, 'd') },
            { label: '后5天', value: dayjs().add(5, 'd') },
            { label: '后7天', value: dayjs().add(7, 'd') },
            { label: '后10天', value: dayjs().add(10, 'd') },
            { label: '后15天', value: dayjs().add(15, 'd') },
            { label: '后20天', value: dayjs().add(20, 'd') },
            { label: '后30天', value: dayjs().add(30, 'd') },
            { label: '后50天', value: dayjs().add(50, 'd') },
            { label: '后90天', value: dayjs().add(90, 'd') },
          ],
          format: 'YYYY-MM-DD HH:mm:ss',
        }}
      />
      <ProFormCascader
        width="xl"
        label="指派征集单位"
        name="assignOrganizationIds"
        placeholder="选择单位"
        extra="不选择，默认推送给所有部门、区县等单位"
        fieldProps={{
          options: treeAssignOrganizationData,
          showSearch: { filter },
          multiple: true,
          removeIcon: false,
          allowClear: false,
          maxTagCount: 'responsive',
          showCheckedStrategy: Cascader.SHOW_CHILD,
        }}
      />
      <ProFormCascader
        width="xl"
        label={
          access.线索征集x配置x管理员
            ? '协助媒体、单位'
            : access.线索征集x配置x部门需求者
            ? '协助媒体、单位'
            : access.线索征集x配置x媒体需求者
            ? '联动媒体'
            : '联动单位'
        }
        name="linkageOrganizationIds"
        placeholder="选择单位"
        extra={'联动部门可看到该选题计划的所有征集线索'}
        fieldProps={{
          options: treeLinkageOrganizationData,
          showSearch: { filter },
          multiple: true,
          removeIcon: false,
          allowClear: false,
          maxTagCount: 'responsive',
          showCheckedStrategy: Cascader.SHOW_CHILD,
        }}
      />

      <ProFormTextArea
        hidden={!isLinkage}
        width="xl"
        label={
          access.线索征集x配置x管理员
            ? '协助媒体、单位'
            : access.线索征集x配置x部门需求者
            ? '协助描述'
            : access.线索征集x配置x媒体需求者
            ? '联动描述'
            : '联动描述'
        }
        name="linkageDescribes"
        fieldProps={{
          rows: 6,
          allowClear: true,
          maxLength: 50000,
          placeholder: '请输入描述（支持换行输入）',
          showCount: true,
        }}
        extra={
          access.线索征集x配置x管理员
            ? '用于协助需求描述'
            : access.线索征集x配置x部门需求者
            ? '用于协助需求描述'
            : access.线索征集x配置x媒体需求者
            ? '用于联动需求描述'
            : '用于联动需求描述'
        }
      />
      {mode === 'apply' && (
        <>
          <ProFormTextArea
            width="xl"
            label="申请描述"
            name="recordDescribes"
            fieldProps={{
              rows: 6,
              allowClear: true,
              maxLength: 50000,
              placeholder: '请输入描述（支持换行输入）',
              showCount: true,
            }}
            extra={'该描述仅供市委宣传部审核使用，不会对外发布'}
          />
        </>
      )}
    </DrawerForm>
  );
};
export default TableTopicManageEdit;
